package com.business.action.weixin;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.business.bean.system.UserBean;
import com.business.wechat.bean.WxUserBean;

import net.sf.rose.jdbc.PageBean;
import net.sf.rose.jdbc.dao.BeanDAO;
import net.sf.rose.jdbc.query.BeanSQL;
import net.sf.rose.jdbc.service.Service;

@Controller
@RequestMapping("/weixin/user")
public class WeixinUserAction {

	/**
	 * 微信用户利用openId绑定用户工号
	 */
	@ResponseBody
	@RequestMapping("/bindUser.do")
	public PageBean bindUser(Service service, UserBean user) {
		PageBean res = new PageBean();
		if (user.getWorkNo() == null || user.getUserName() == null || user.getOpenId() == null) {
			res.setSuccess(false);
			res.setMessage("姓名、工号和openId三个参数一个不能缺少！");
			return res;
		}
		BeanDAO dao = new BeanDAO(service);
		BeanSQL query = dao.getQuerySQL();
		UserBean bean = new UserBean();
		bean.setWorkNo(user.getWorkNo());
		bean.setUserName(user.getUserName());
		query.createSql(bean);
		bean = dao.get();
		// 如果根据姓名和工号不能找到员工数据
		if (bean == null) {
			res.setSuccess(false);
			res.setMessage("根据姓名(" + user.getUserName() + ")和工号(" + user.getWorkNo() + ")没有找到员工数据！");
			return res;
		}
		UserBean userBean = new UserBean();
		userBean.setUserID(bean.getUserID());
		userBean.setOpenId(user.getOpenId());
		userBean.setMobile(user.getMobile());
		query.createUpdateSql(userBean);
		if (dao.update() < 1) {
			res.setSuccess(false);
			res.setMessage("绑定失败！");
			return res;
		}
		res.setData(userBean);
		return res;
	}

	/**
	 * 微信用户利用openId解除绑定用户
	 */
	@ResponseBody
	@RequestMapping("/unBindUser.do")
	public PageBean unBindUser(Service service, String openId) {
		PageBean res = new PageBean();
		BeanDAO dao = new BeanDAO(service);
		BeanSQL query = dao.getQuerySQL();
		query.setEntityClass(UserBean.class);
		query.createSql("openId", openId);
		UserBean bean = dao.get();
		// 如果根据openId没有找到用户数据
		if (bean == null) {
			res.setSuccess(false);
			res.setMessage("根据openId(" + openId + ")没有找到员工数据！");
			return res;
		}
		query.setSQL("update SYS_USER set openId=null where openId=?");
		query.addParameter(openId);
		if (dao.update() < 1) {
			res.setSuccess(false);
			res.setMessage("解除绑定失败！");
			return res;
		}
		return res;
	}

	/**
	 * 根据openId获取用户
	 */
	@ResponseBody
	@RequestMapping("/get.do")
	public PageBean get(Service service, String openId) {
		PageBean res = new PageBean();
		BeanDAO dao = new BeanDAO(service);
		BeanSQL query = dao.getQuerySQL();
		query.setEntityClass(WxUserBean.class);
		query.createSql("openId", openId);
		res.setData(dao.get());
		return res;
	}

}
